const fs = require('fs');
const express = require('express');
const bodyParser = require('body-parser');
const { axurl } = require('./src/utils/axurl');

const app = express();
// body parser
// app.use(bodyParser.json());
const urlencodedParser = bodyParser.urlencoded({ extended: true });

// 设置跨域访问
app.all('*', (req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
    res.header('X-Powered-By', ' 3.2.1');
    next();
});

function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}

function guid() {
    return `${S4() + S4()}-${S4()}-${S4()}-${S4()}-${S4()}${S4()}${S4()}`;
}

/** 获取json文件名称 */
function getFileName(req) {
    const { path } = req;
    // const api = /\/[a-zA-Z-]+/.exec(path);
    const matchPaths = path.match(/\/[a-zA-Z-]+/g);
    let filename = '';
    if (matchPaths && matchPaths.length > 1) {
        filename = matchPaths[1].substr(1);
    }
    return `./database/${filename}.json`;
}

/** 获取数据 */
function queryData(filename) {
    const data = fs.readFileSync(filename);
    if (data == '') {
        return { list: [], total: 0, success: true };
    }
    return JSON.parse(data);
}

/** 写入数据 */
function writeData(filename, str) {
    let flag = !0;
    fs.writeFile(filename, str, err => {
        if (err) {
            flag = !1;
            console.error('----写入失败----');
        } else {
            console.log('----写入成功----');
        }
    });
    return flag;
}

/** 读取普通数据方法 */
function readx(req, res) {
    res.header('Content-Type', 'application/json;charset=utf-8');

    const filename = getFileName(req);
    /** json数据 */
    const json = { data: queryData(filename), success: true };

    res.end(JSON.stringify(json));
}

/** 读取列表方法 */
function read(req, res) {
    res.header('Content-Type', 'application/json;charset=utf-8');

    const filename = getFileName(req);
    /** 请求参数 */
    const { query } = req;
    /** json数据 */
    const json = { ...queryData(filename), success: true };

    /** 有查询参数时，查询数据 */
    if (Object.keys(query).length > 0) {
        for (var k in query) {
            if (k != 'currentPage' && k != 'pageSize') {
                json.list = json.list.filter(u => u[k] && u[k].indexOf(query[k]) > -1);
            }
        }
    }

    /** 设置数据总数 */
    json.total = json.list.length;

    /** 分页 */
    const { currentPage } = query;
    const { pageSize } = query;
    if (currentPage && pageSize) {
        const current = parseInt(currentPage);
        const size = parseInt(pageSize);
        const start = (current - 1) * size;
        const end = current * size;
        json.list = json.list.filter((f, idx) => {
            if (start <= idx && idx < end) {
                return true;
            }
            return false;
        });
    }
    res.end(JSON.stringify(json));
}

/** 创建方法 */
function create(req, res) {
    res.header('Content-Type', 'application/json;charset=utf-8');

    const filename = getFileName(req);
    /** 请求参数 */
    const query = req.body;
    // 返回内容
    const response = {};
    // 获取数据
    const json = queryData(filename);
    json.list.push({
        id: guid(),
        ...query,
    });
    json.total = json.list.length;
    const b = writeData(filename, JSON.stringify(json));
    if (b) {
        response.success = true;
        response.message = '新增成功';
    } else {
        response.success = false;
        response.message = '新增失败';
    }
    res.end(JSON.stringify(response));
}

/** 修改方法 */
function update(req, res) {
    res.header('Content-Type', 'application/json;charset=utf-8');

    const filename = getFileName(req);
    /** 请求参数 */
    const query = req.body;
    // 返回内容
    const response = {};
    const _id = query.id || '';
    if (!_id || _id == '') {
        response.success = false;
        response.message = 'id不能为空';
    } else {
        // 获取数据
        const json = queryData(filename);
        // 判断id是否存在
        let a = !0;
        for (let i = 0; a && i < json.list.length; i++) {
            if (json.list[i].id == _id) {
                json.list[i] = {
                    ...json.list[i],
                    ...query,
                };
                a = !1;
                break;
            }
        }
        if (a) {
            response.success = false;
            response.message = '该id不存在';
        } else {
            const b = writeData(filename, JSON.stringify(json));
            if (b) {
                response.success = true;
                response.message = '修改成功';
            } else {
                response.success = false;
                response.message = '修改失败';
            }
        }
    }
    res.end(JSON.stringify(response));
}

/** 修改方法（直接整体修改Json） */
function updateJson(req, res) {
    res.header('Content-Type', 'application/json;charset=utf-8');

    const filename = getFileName(req);
    /** 请求参数 */
    const query = req.body;
    // 返回内容
    const response = {};

    const b = writeData(filename, query.json);
    if (b) {
        response.success = true;
        response.message = '修改成功';
    } else {
        response.success = false;
        response.message = '修改失败';
    }

    res.end(JSON.stringify(response));
}

/** 删除方法 */
function destroy(req, res) {
    res.header('Content-Type', 'application/json;charset=utf-8');

    const filename = getFileName(req);
    const query = req.body;
    const _id = query.id || '';
    // 返回内容
    const response = {};
    if (!_id || _id == '') {
        response.success = false;
        response.message = 'id不能为空';
    } else {
        // 获取数据
        const json = queryData(filename);
        if (json.list.find(f => f.id == _id)) {
            for (let i = 0; i < json.list.length; i++) {
                if (json.list[i].id == _id) {
                    json.list.splice(i, 1);
                    break;
                }
            }
            json.total = json.list.length;
            const b = writeData(filename, JSON.stringify(json));
            if (b) {
                response.success = true;
                response.message = '删除成功';
            } else {
                response.success = false;
                response.message = '删除失败';
            }
        } else {
            response.success = false;
            response.message = '该id不存在';
        }
    }
    res.end(JSON.stringify(response));
}

axurl.forEach(f => {
    if (f.indexOf('/readx') > -1) {
        app.get(f, readx);
    } else if (f.indexOf('/read') > -1) {
        app.get(f, read);
    } else if (f.indexOf('/create') > -1) {
        app.post(f, urlencodedParser, create);
    } else if (f.indexOf('/updateJson') > -1) {
        app.post(f, urlencodedParser, updateJson);
    } else if (f.indexOf('/update') > -1) {
        app.post(f, urlencodedParser, update);
    } else if (f.indexOf('/destroy') > -1) {
        app.post(f, urlencodedParser, destroy);
    }
});

app.listen(10001, () => {
    console.log('数据服务已启动，请访问: http://localhost:10001');
});
